package wjb.test.mawen.mawen.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import wjb.test.mawen.mawen.mapper.QuestionMapper;
import wjb.test.mawen.mawen.model.Question;
import wjb.test.mawen.mawen.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class PublishController {
    @Autowired
    private QuestionMapper questionMapper;

    @GetMapping("/publish")
    public String toPublish(){
        return "publish";
    }
    @PostMapping("/publish")
    public String postquestion(@RequestParam(value = "title",required = false) String title,
                               @RequestParam( value = "description",required = false) String description,
                               @RequestParam(value = "tag",required = false) String tag,
                               HttpServletRequest httpServletRequest,
                               Model model){
        httpServletRequest.getSession().setAttribute("title",title);
        httpServletRequest.getSession().setAttribute("description",description);
        httpServletRequest.getSession().setAttribute("tag",tag);
        StringBuffer msg=new StringBuffer();
        if (title==null || "".equals(title.trim())){
            msg.append("【问题标题】");
        }
        if (description==null || "".equals(description.trim())){
            msg.append("【问题描述】");
        }
        if (tag==null || "".equals(tag.trim())){
            msg.append("【问题标签】");
        }
        if (msg.length()!=0){
            msg.append("不允许为空！");

        }
        httpServletRequest.getSession().setAttribute("currentpage","publish");
        User o= (User) httpServletRequest.getSession().getAttribute("user");
        if(o==null || msg.length() !=0){
            if(o!=null){
                httpServletRequest.getSession().setAttribute("msg",msg.toString());
            }else {
                httpServletRequest.getSession().setAttribute("msg",msg.append("请先登录系统，再发表话题！"));
            }
            return "publish";
        }

        Question question=new Question();
        question.setTitle(title);
        question.setDescription(description);
        question.setTag(tag);
        question.setGmt_create(System.currentTimeMillis());
        question.setGmt_modified(System.currentTimeMillis());
        question.setUserid(o.getId());
        questionMapper.addQuestion(question);
        return "redirect:/";
    }
}
